package P3;

import NIOCommunication.NIOProcessor;
import NIOCommunication.NIOProcessorCloseContextCommand;
import NIOCommunication.NIOSocketContext;
import java.nio.channels.SocketChannel;

public class WorkerInterface extends CoordinationContext
{
    private Coordinator mCoordinator;
    private boolean mClosed = false;
    
    public WorkerInterface(Coordinator coordinator, NIOProcessor processor, SocketChannel context)
    {
        super(processor, context);
        mCoordinator = coordinator;
    }
    
    @Override
    public void OnNewMessage(String message)
    {
        if(message.startsWith("CrawlResult\n"))
        {
            CrawlResult result = new CrawlResult();
            result.LoadFromString(message);
            mCoordinator.OnNewResult(result);
            return;
        }
        
        if(message.startsWith("Goodbye"))
        {
            System.out.println("Worker says bye!");
            mNIOProcessor.QueueCommand(new NIOProcessorCloseContextCommand(this));
            return;
        }
        
        System.out.println("Incoming message: " + message);
    }
    
    @Override
    public void OnChannelClosed(NIOSocketContext context)
    {
        mClosed = true;
        mCoordinator.OnWorkerDisconnected(this);
    }
    
    public boolean IsClosed()
    {
        return mClosed;
    }
}
